package com.hsgene.util.mq.rocket.consumer;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 消息消费者
 *
 * @author wangbing
 * @version 1.0
 * @date 2018/11/9 14:32
 * Copyright: Copyright (c) 2019
 */
public class RocketMQTopicListener implements MessageListener {

    private final static Logger LOGGER = LoggerFactory.getLogger(RocketMQTopicListener.class);

    private Map<String, AbstractRocketMQListener> listenerMap = Maps.newHashMap();

    public RocketMQTopicListener() {
    }

    public RocketMQTopicListener(Map<String, AbstractRocketMQListener> listenerMap) {
        this.listenerMap = listenerMap;
    }

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        AbstractRocketMQListener listener = listenerMap.get(message.getTag());
        if (listener == null) {
            LOGGER.warn("收到消息，没有对应的消息监听处理者！Message = {}", message);
            return Action.ReconsumeLater;
        }
        return listener.consume(message, consumeContext);
    }

    public Map<String, AbstractRocketMQListener> getListenerMap() {
        return listenerMap;
    }

    public void setListenerMap(Map<String, AbstractRocketMQListener> listenerMap) {
        this.listenerMap = listenerMap;
    }
}
